<template>
  <div>
    <el-input v-model="inputVal" class="w-50 m-2" placeholder="请输入你想找的货物" :suffix-icon="Search" @input="iptChange"
      clearable />
    <div class="searchBox" v-if="searchList.length != 0">
      <div class="searchList" v-for="(item, index) in searchList" :key="index" @click="clickItem(item)">
        <div class="left">
          {{ item?.value }}
        </div>
        <div class="right">
          {{ item?.categoryName }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, Ref, watch } from "vue";
import { Search } from '@element-plus/icons-vue'
import { HttpRequest } from "@/http";
const props = defineProps({
  //双向绑定的值
  modelValue: {
    type: String,
    required: false,
    default: "",
  },
});
const emits = defineEmits<{
  (e: "update:modelValue", val: any): void;
  (e: "onChange", val: any): void;
}>();
const inputVal: Ref<string> = ref(props.modelValue || "");
const searchList: Ref<any[]> = ref([])
watch(
  () => props.modelValue,
  (val: any) => {
    inputVal.value = val || "";
  },
  { deep: true }
);
watch(
  () => inputVal.value,
  (val: any) => {
    if (!val) {
      searchList.value = []
    }
  },
  {
    deep: true,
    immediate: true
  }
);
// 去除首位空格
function trimStr(str: string) {
  if (!str) return ''
  return str.replace(/\s/g, "");
}
let timer
const iptChange = async (e: any) => {
  emits("onChange", e);
  if (!e) {
    searchList.value = []
    return
  }
  const value = trimStr(e)
  timer = null
  timer = setTimeout(async () => {
    let res = await new HttpRequest(`/dictionary?value=${value}`).get();
    searchList.value = res.data
  }, 1000)
}
// const iptBlur = () => {
//   searchList.value = []
// }
const clickItem = (item: any) => {
  emits("update:modelValue", item.value);
  emits("onChange", item);
  searchList.value = []
  inputVal.value = item.value

}

//设置当前值
const setData = (value: string) => {
  inputVal.value = value;
};
//获取当前值
const getData = () => {
  return inputVal.value;
};
defineExpose({ setData, getData });
</script>

<style scoped lang="scss">
.searchBox {
  width: 100%;
  max-height: 200px;
  box-sizing: border-box;
  overflow: auto;
  position: absolute;
  left: 0;
  top: 33px;
  background-color: #fff;
  cursor: pointer;
  z-index: 99;
  border: 1px solid #bbb;
}

.searchList {
  box-sizing: border-box;
  height: 30px;
  padding: 0 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #1b1b1b;
  border-bottom: 1px solid #bbb;
  background-color: #fff;

  &:last-child {
    border-bottom: none;
  }

  .right {
    margin: 10px;
    text-align: center;
    border-radius: 16px;
    white-space: nowrap;
  }

}
</style>